package com.jzz.eletuanbackend.interceptors;

import com.alibaba.fastjson.JSON;
import com.jzz.eletuanbackend.config.TokenHttpServletRequestWrapper;
import com.jzz.eletuanbackend.service.AuthService;
import com.jzz.eletuanbackend.util.Msg;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class BaseTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private AuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,accept,token,set-cookie");
        response.setHeader("Access-Control-Expose-Headers", "Token");
        response.setCharacterEncoding("utf-8");

        if (request.getMethod().toLowerCase().equals("options")) {
            response.setStatus(202);
            return true;
        }

        /* 这里AJAX对Cookie的操作并不友好，所以把Token放到Header里而不是Cookie里 */
        String token = "";
        if (request.getHeader("Token") != null) {
            token = request.getHeader("Token");
        }

        String rawUserId = getRawUserId(token);

        if (!(request instanceof TokenHttpServletRequestWrapper)) {
            request = new TokenHttpServletRequestWrapper(request);
        }

        request.getParameterMap().put("user_id", new String[]{rawUserId.substring(Math.min(1, rawUserId.length()))});

        if (checkToken(rawUserId)) {
            return true;
        } else {
            PrintWriter printWriter = response.getWriter();
            if (token == null || rawUserId.isEmpty()) {
                printWriter.println(JSON.toJSONString(Msg.err(401, "请登录后重试")));
                response.setStatus(401);
            } else {
                printWriter.println(JSON.toJSONString(Msg.err(403, "未授权的操作")));
                response.setStatus(403);
            }

            printWriter.flush();
            printWriter.close();
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    String getRawUserId(String token) {
        return authService.getUserId(token);
    }

    boolean checkToken(String rawId) {
        return true;
    }

}